package com.openingedu.mba.util;

import java.io.UnsupportedEncodingException;

import android.os.Message;

import com.openingedu.mba.common.CommConsts;
import com.openingedu.mba.http.HttpHandler;
import com.openingedu.mba.http.LightAsyncHttp;
import com.openingedu.mba.http.RequestParams;
import com.openingedu.mba.http.SimpleResponseHandler;


public class HttpUtil {

	private static HttpUtil instance;
	private HttpHandler uiHandler;
	public static HttpUtil getInstance() {
		if (instance == null) {
			instance = new HttpUtil();
		}
		return instance;
	}
	
	final SimpleResponseHandler responseHandler = new SimpleResponseHandler() {

		@Override
		public void onStart(String url) {
			Message msg = Message.obtain(uiHandler, HttpHandler.START, "[START] {" + url
					+ "}");
			uiHandler.sendMessage(msg);
		}

		@Override
		public void onCancel(int requestId, String url) {
			Message msg = Message.obtain(uiHandler, HttpHandler.CANCEL, "[ID] = " + requestId + ", [CANCLE] {" + url
					+ "}");
			uiHandler.sendMessage(msg);
		}

		@Override
		public void onError(Throwable error, int requestId, String url) {
			Message msg = Message.obtain(uiHandler, HttpHandler.ERROR, "[ID] = " + requestId + ", [ERROR] {" + url
					+ "} = " + error.getMessage());
			uiHandler.sendMessage(msg);
		}

		@Override
		public void successWithTextData(String content, int requestId, String url) {
			Message msg = Message.obtain(uiHandler, HttpHandler.SUCCESS, content);
			uiHandler.sendMessage(msg);
		}

		@Override
		public void successWithBinaryData(byte[] binary, int requestId, String url) {
			Message msg = Message.obtain(uiHandler, HttpHandler.SUCCESS, "[ID] = " + requestId + ", [BIN] {" + url + "} = " + binary.length);
			uiHandler.sendMessage(msg);
		}
	};
	
	public void post(String url, RequestParams params, HttpHandler uiHandler) throws UnsupportedEncodingException {
		try {
			this.uiHandler = uiHandler;
			final int requestId = LightAsyncHttp.getInstance().post(url, params, responseHandler);
			Message msg = Message.obtain(uiHandler, 0, "[ID] = " + requestId);
			this.uiHandler.sendMessage(msg);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void get(String url, RequestParams params, HttpHandler uiHandler) {
		this.uiHandler = uiHandler;
		final int requestId = LightAsyncHttp.getInstance().get(url, params, responseHandler);
		Message msg = Message.obtain(uiHandler, 0, "[ID] = " + requestId);
		this.uiHandler.sendMessage(msg);
	}

	public void post(RequestParams params, HttpHandler paperHttpHandler) throws UnsupportedEncodingException {
		post(CommConsts.siteURL, params, paperHttpHandler);
	}
	
}
